let mediaRecorder;
let recordedChunks = [];

// 录屏功能
async function startRecording() {
    recordedChunks = [];

    const stream = await navigator.mediaDevices.getDisplayMedia({
        video: {
            displaySurface: "browser",
            frameRate: 30
        }
    });

    mediaRecorder = new MediaRecorder(stream, {
        mimeType: 'video/webm;codecs=vp9'
    });

    mediaRecorder.ondataavailable = (event) => {
        if (event.data.size > 0) {
            recordedChunks.push(event.data);
        }
    };

    // 注册停止事件
    mediaRecorder.onstop = () => {
        const blob = new Blob(recordedChunks, {
            type: 'video/webm'
        });

        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');

        a.href = url;
        a.download = 'code-animation.webm';
        a.click();

        stream.getTracks().forEach(track => track.stop());
    };

    document.getElementById('recordButton').disabled = true;
    document.getElementById('downloadButton').disabled = false;

    setTimeout(() => {
        mediaRecorder.start();
    }, 1000);

    setTimeout(() => {
        startTyping();
    }, 1000);
}

// 停止录屏功能
function stopRecording() {
    if (mediaRecorder && mediaRecorder.state !== 'inactive') {
        mediaRecorder.stop();
        document.getElementById('recordButton').disabled = false;
        document.getElementById('downloadButton').disabled = true;
    }
}